package top.sinno;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipOverwriter {

    public static void overwriteFileInZip(String zipFilePath, String fileToOverwritePath, String newContent) throws IOException {
        File tempFile = new File(zipFilePath + ".tmp");

        try (
                InputStream is = new FileInputStream(zipFilePath);
                OutputStream os = new FileOutputStream(tempFile);
                ZipInputStream zis = new ZipInputStream(is);
                ZipOutputStream zos = new ZipOutputStream(os)
        ) {
            ZipEntry entry;
            boolean found = false;

            while ((entry = zis.getNextEntry()) != null) {
                zos.putNextEntry(new ZipEntry(entry.getName()));
                System.out.println(entry.getName());
                if (entry.getName().equals(fileToOverwritePath)) {
                    System.out.println("over write");
                    found = true;
                    zos.write(newContent.getBytes());
                } else {
                    System.out.println("copy write");
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = zis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                }

                zos.closeEntry();

//                if (found) {
//                    break; // Already found and overwritten the file, no need to continue.
//                }
            }
        }

        // Delete the original zip file
        (new File(zipFilePath)).delete();

        // Rename the temp file to zip file name
        tempFile.renameTo(new File(zipFilePath));
    }

    public static void main(String[] args) {
        try {
            String zipFilePath = "D:\\Documents\\ziptest\\app.zip"; // 多层嵌套的ZIP文件路径
            String fileToOverwritePath = "lcdp.zip\\a.txt"; // 要覆写的文件路径
            String newContent = "New content for the file"; // 新文件内容

            overwriteFileInZip(zipFilePath, fileToOverwritePath, newContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}